package com.sky.zzh.today;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;

import com.next.intf.ITaskListener;
import com.next.net.SHGet;
import com.next.net.SHPost;
import com.next.net.SHTask;
import com.sky.widget.SHDialog;
import com.sky.widget.sweetdialog.SweetDialog;
import com.sky.zzh.R;
import com.sky.zzh.util.ConfigDefinition;
import com.sky.zzh.util.UserInfoManager;

public class SleepQualityReport extends Activity implements ITaskListener {
  private CheckBox textViewLoseSleep, textViewDeepSleep, textViewNightmare;
  private SHGet tagTask;
  private SHPost tagUpdate;
  private String fromDate = "20150926", endDate = "20150927";
  private static final String TAG4 = "失眠";
  private static final String TAG5 = "熟睡";
  private static final String TAG6 = "噩梦";
  private Button buttonBack, buttonUpdate;
  private ArrayList<String> SleepAfter = new ArrayList<String>();
  private MyCheckChangedListener mMyCheckChangedListener;
  private boolean isPre=false;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sleepqualityreport);
    mMyCheckChangedListener=new MyCheckChangedListener();
    textViewDeepSleep = (CheckBox) findViewById(R.id.textViewDeepSleep);
    textViewLoseSleep = (CheckBox) findViewById(R.id.textViewLoseSleep);
    textViewNightmare = (CheckBox) findViewById(R.id.textViewNightmare);
    textViewDeepSleep.setOnCheckedChangeListener(mMyCheckChangedListener);
    textViewLoseSleep.setOnCheckedChangeListener(mMyCheckChangedListener);
    textViewNightmare.setOnCheckedChangeListener(mMyCheckChangedListener);

    buttonBack = (Button) findViewById(R.id.buttonBack);
    buttonUpdate = (Button) findViewById(R.id.btn_rightAccomplish);
    buttonBack.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        onBackPressed();
      }
    });
    buttonUpdate.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
    	if (isPre) {
			Toast.makeText(getApplicationContext(), "日子已过去，只能查看", Toast.LENGTH_SHORT).show();
			return;
		}
        JSONArray array = new JSONArray();
        String currentDateandTime =
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
        try {
          for (String i : SleepAfter) {
            array.put(new JSONObject().put("Tag", i).put("TagType", "1")
                .put("UserTagDate", currentDateandTime));
          }
        } catch (JSONException e) {
          e.printStackTrace();
        }
        System.out.println("SleepAfter" + SleepAfter);
        StringBuffer sb = new StringBuffer();
        sb.append(ConfigDefinition.URL);
        sb.append("user/UpdateUserTag");
        tagUpdate = new SHPost();
        tagUpdate.setListener(SleepQualityReport.this);
        tagUpdate.setUrl(sb.toString());
        tagUpdate.getTaskArgs().put("UserID", UserInfoManager.getInstance().getUserId());
        tagUpdate.getTaskArgs().put("Tags", array);
        tagUpdate.start();
      }
    });

    fromDate = getIntent().getStringExtra("fromDate");
    endDate = getIntent().getStringExtra("endDate");
    String currentDate =
            new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());
    if (Integer.valueOf(currentDate)>Integer.valueOf(endDate)) {
		isPre=true;
	}
    requestData(fromDate, endDate);
  }


  @Override
  public void onTaskFinished(SHTask task) throws Exception {
    SHDialog.dismissProgressDiaolg();
    JSONObject json = new JSONObject(task.getResult().toString());
    System.out.println("json:" + json);
    if (task == tagTask) {
      try {
        if ("200".equals(json.optString("ReturnCode"))) {
          JSONArray array = json.optJSONArray("Tags");
          int size = array.length();
          JSONObject obj = null;
          for (int i = 0; i < size; i++) {
            obj = array.getJSONObject(i);
            String TAG = obj.optString("Tag");
            int TagType = obj.optInt("TagType");
            if (TAG.equals(TAG4)) {
              // textViewLoseSleep.setBackgroundColor(parseColor);
              textViewLoseSleep.setChecked(true);
            }
            if (TAG.equals(TAG5)) {
              // textViewDeepSleep.setBackgroundColor(parseColor);
              textViewDeepSleep.setChecked(true);
            }
            if (TAG.equals(TAG6)) {
              // textViewNightmare.setBackgroundColor(parseColor);
              textViewNightmare.setChecked(true);
            }
          }
          if (isPre) {
			textViewLoseSleep.setEnabled(false);
			textViewDeepSleep.setEnabled(false);
			textViewNightmare.setEnabled(false);
            }
        } else {
          SHDialog.dismissProgressDiaolg();
          new SweetDialog(this, SweetDialog.ERROR_TYPE).setTitleText("提示3")
              .setContentText(json.optString("ErrorMessage")).show();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else if (task == tagUpdate) {
      if ("200".equals(json.optString("ReturnCode"))) {
        Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();
        finish();
      }
    }
  }


  @Override
  public void onTaskFailed(SHTask task) {
    // TODO Auto-generated method stub

  }


  @Override
  public void onTaskUpdateProgress(SHTask task, int count, int total) {
    // TODO Auto-generated method stub

  }


  @Override
  public void onTaskTry(SHTask task) {
    // TODO Auto-generated method stub

  }

  private void requestData(String fromDate, String endDate) {
    SHDialog.dismissProgressDiaolg();
    if (tagTask != null) {
      tagTask.cancel(true);
    }
//    SHDialog.ShowProgressDiaolg(this);
    tagTask = new SHGet();
    tagTask.setListener(this);
    StringBuffer sb = new StringBuffer();
    sb.append(ConfigDefinition.URL);
    sb.append("user/UserTags?UserId=");
    sb.append(UserInfoManager.getInstance().getUserId());
    sb.append("&");
    sb.append("FromDate=");
    sb.append(fromDate);
    sb.append("&");
    sb.append("EndDate=");
    sb.append(endDate);
    tagTask.setUrl(sb.toString());
    tagTask.start();
  }

  class MyCheckChangedListener implements OnCheckedChangeListener {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
      if (isChecked) {
        SleepAfter.add(buttonView.getText().toString());
      } else {
        SleepAfter.remove(buttonView.getText().toString());
      }
    }

  }

}
